import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:yp/config/config.dart';
import 'package:yp/helper.dart';
import 'package:yp/router.dart';
import 'package:yp/services/api.dart';
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/utils/util.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

import 'state.dart';

class MallLoginLogic extends GetxController {
  final state = MallLoginState();
  final arguments = Get.arguments;

  dynamic wxcode;
  @override
  void onInit() async {
    super.onInit();

    state.phoneTextController = TextEditingController();
    state.phoneFocusNode = FocusNode();

    state.passwordTextController = TextEditingController();
    state.passwordFocusNode = FocusNode();

    state.phoneTextController.text = SpUtil.getString('number');
    state.choosePrivacyAgreement = false;
    state.loginBool = false;
    state.passwordShow = true;

    if (!kIsWeb) {
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      state.version = packageInfo.version ?? "";
      state.buildNumber = packageInfo.buildNumber ?? "";
    } else {
      state.version = "";
      state.buildNumber = "";
    }
    update();
  }

  @override
  void onReady() {
    super.onReady();
    fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((event) {
      if (event is fluwx.WeChatAuthResponse) {
        int errCode = event.errCode;
        if (errCode == 0) {
          //print('wx listen----------$errCode--------${event.code}');
          state.wxCode = event.code;
          login();
        } else if (errCode == -4) {
          Get.offNamed(RouteConfig.mallLogin);
        } else if (errCode == -2) {
          Get.offNamed(RouteConfig.mallLogin);
        }
        //state.wxCode = event.code;
        //login();
        //print('wx listen2----------${event.code}');
      }
    });
  }

  // 隐私协议 选择事件
  void choosePrivacyAgreement(bool chooseBool) {
    state.choosePrivacyAgreement = chooseBool;
    print('--------  choosePrivacyAgreement ');
    if (state.phoneTextController.text != '' &&
        state.passwordTextController.text != '' &&
        state.choosePrivacyAgreement) {
      state.loginBool = true;
    } else {
      state.loginBool = false;
    }
    update();
  }

  // 输入框内容改变 事件
  void textControllerClick() {
    print('11111  textControllerClick');
    if (state.phoneTextController.text != '' &&
        state.passwordTextController.text != '' &&
        state.choosePrivacyAgreement) {
      state.loginBool = true;
    } else {
      state.loginBool = false;
    }
    update();
  }

  // 密码登录
  void onSubmit() {
    if (state.choosePrivacyAgreement == false) {
      toast('请先阅读并同意勾选服务协议');
      return;
    }
    var params = {
      "account": state.phoneTextController.text,
      "password": state.passwordTextController.text,
      'use_platform': 2,
    };
    Api.login(params).listen((event) {
      if (event["code"] != 0) {
        if (event["code"] == 401) {
          toast(event["message"]);
        }
        else {
          toast('登录错误：${event["message"]}');
        }
      } else {
        SpUtil.putString('empeName', event["usr_name"] ?? '');
        SpUtil.putInt('empeNumId', event["usr_num_id"]);
        SpUtil.putString('token', event["access_token"]);
        SpUtil.putString('number', state.phoneTextController.text);
        SpUtil.putInt(Config.IS_CHANGE_SHOP, 0);
        if (event["sign"] != null && event["sign"] != '') {
          SpUtil.putString('usr_phone_num', event["usr_phone_num"]);
          SpUtil.putString('sign', event["sign"]);
          SpUtil.putInt('time_stamp', event["time_stamp"]);
        }
        SpUtil.remove(Config.GET_SHOP_INFO);
        toast("登录成功");
        if (arguments != null) {
          argumentsRouter(arguments);
        } else {
          Get.offAllNamed(RouteConfig.main);
        }
      }
    });
  }

  // 微信登录
  void loginWX() async {
    var result = await fluwx.isWeChatInstalled;
    if (result) {
      Config.ShowLoginPageLeftTip=false;
      fluwx
          .sendWeChatAuth(
              scope: 'snsapi_userinfo', state: 'wechat_sdk_demo_test')
          .then((value) {
        Config.ShowLoginPageLeftTip=true;
      })
          .catchError((onError) {
        Config.ShowLoginPageLeftTip=true;
        print(onError);
      });

    } else {
      toast('未安装微信');
    }
  }

  void login() {
    print(
        'appid--------${Config.WECHAT_APPID}------------wxcode========${state.wxCode}');
    if (state.wxCode == wxcode) return;

    wxcode = state.wxCode;
    var params = {
      "appid": Config.WECHAT_APPID, 
      "code": state.wxCode,
      'use_platform': 2,
    };
    print('weixin login params:$params');
    Api.wxLogin(params).listen((event) {
      var code = event['code'];
      print('wxLogin code:$code');
      //code = -147213;
      if (code == -147213) {
        var thirdAccessToken = event['third_access_token'];
        var thirdContactNo = event['third_contact_no'];
        var thirdContactType = event['third_contact_type'];
        Get.offNamed(RouteConfig.userBind +
            '?thirdAccessToken=$thirdAccessToken&thirdContactNo=$thirdContactNo&thirdContactType=$thirdContactType');
      } else if (code == 0) {
        SpUtil.putString('empeName', event["usr_name"]);
        SpUtil.putInt('empeNumId', event["usr_num_id"]);
        SpUtil.putString('token', event["access_token"]);
        // SpUtil.putString('number', event["third_contact_no"]); 本地不用再存储

        //print('wxlogin number:${state.phoneTextController.text}');
        SpUtil.putInt(Config.IS_CHANGE_SHOP, 0);
        if (event["sign"] != null && event["sign"] != '') {
          SpUtil.putString('usr_phone_num', event["usr_phone_num"]);
          SpUtil.putString('sign', event["sign"]);
          SpUtil.putInt('time_stamp', event["time_stamp"]);
          SpUtil.putString('number', event["usr_phone_num"]); //
        } else {
          SpUtil.putString('number', ''); //
        }
        SpUtil.remove(Config.GET_SHOP_INFO);
        toast("登录成功");
        Get.offAllNamed(RouteConfig.main);
      } else {
        if (code == -147201) {
          //有别的插件拦截使用，因此忽略这个code
        } else {
          if (event["code"] == 401) {
            toast(event["message"]);
          }
          else {
            toast('登录错误：${event["message"]}');
          }
        }
      }
    });
  }
}
